import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:package_info/package_info.dart';
import 'package:yp/config/config.dart';

///
/// App升级请求,访问zrhsh.com接口
///
class CGHttpClient {

  static const Duration timeOut = Duration(seconds: 30);

  static const String VersionInfo = 'updateInfo';

  static const CGHSHUpdateVersion = "/controller/app/getAppVersion.do";       //app版本升级
  static const UploadAppCode = "zrhsh";            //升级的AppCode(慧帮手：·， 慧享客:nrp3_hxk)

  static startRequest(String subUrl, Map parameter,
      void Function(int code, Map data) onResult,{bool needAppverify}) async {

    final httpClient = HttpClient();
    httpClient.connectionTimeout = timeOut;

    // 设置代理抓包
//    httpClient.findProxy = (url) {
//      return HttpClient.findProxyFromEnvironment(url, environment: {"http_proxy": 'http://10.10.18.95:8888',});
//    };

    try {
      Uri uri = Uri.http(Config.CGHSHBaseUrl, subUrl, new Map<String, String>.from(parameter));
      var request = await httpClient.postUrl(uri);

      print('请求参数');
      print(parameter);
      print('请求地址');
      print(Config.CGHSHBaseUrl + subUrl);

      var response = await request.close().timeout(timeOut);
      if (response.statusCode == HttpStatus.ok) {
        var json = await response.transform(utf8.decoder).join();
        var data = jsonDecode(json);
        print('请求结果:' + data.toString());
        onResult(0, data);

      } else {
        print('请求失败');
        print(response.statusCode);
        onResult(-1, {'message': '请求失败', 'msg': '请求失败'});
      }
    }catch(e){
      print(e.toString());
      onResult(-1, {'message': '请求失败', 'msg': '请求失败'});
    }
  }


  ///获取APP版本
  static getAppVersion(void Function(String version) onResult) async {
    PackageInfo.fromPlatform().then((PackageInfo packageInfo) {

      if(Platform.isIOS){
        onResult(packageInfo.version.toString());

      }else{
        onResult(packageInfo.version.toString());
      }
    });
  }
}
